<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	
	public function actionIndex()
	{
		$model=new Item;
		$model->scenario='create';
        
		if(isset($_POST['Item']))
        {
            $model->attributes=$_POST['Item'];
            $model->uploadedFile=CUploadedFile::getInstance($model,'uploadedFile');
            if($model->uploadedFile!=null)
            {
				date_default_timezone_set('America/New_York');
            	$model->end_time=date("Y-m-d H:i:s");
            	$model->guid=md5(uniqid());
            	$model->hash=hash_file('md5', $model->uploadedFile->getTempName());
            	$model->version=1;
            	$model->file_path='data'.DIRECTORY_SEPARATOR.$_POST['Item']['email_address'].DIRECTORY_SEPARATOR.$model->guid.DIRECTORY_SEPARATOR.$model->version;
            	$model->size=$model->uploadedFile->getSize();
            	
            	$transaction=Yii::app()->db->beginTransaction();
            	if($model->save())
            	{
            		$this->createFolder($model->file_path);
            		$result=$model->uploadedFile->saveAs($model->file_path);
            		if($result)
            		{
            			$transaction->commit();
            			$email=new Email;
		            	$to=$model->email_address;
		            	$from_name='admin';
		            	$subject="You have successfully uploaded the file "."'".$model->uploadedFile->getName()."'";
		            	$emailResult=$email->sendEmail($to, $from_name, $subject, Email::$VIEW_UPLOAD, array('ViewListAddress'=>Yii::app()->request->getServerName().Yii::app()->request->baseUrl.'/manage/viewList?guid='.$model->guid));
		            	if($emailResult==false)
		            		echo $email->getError();    		
            		}
            		else
            		{
            			$transaction->rollback();
            			echo $model->uploadedFile->getError();
            		}
            	}
            	else
            	{
            		$transaction->rollback();
            		print_r($model->getErrors());
            	}
            }
            else
            	echo "please select an item";
        }
        $this->render('index', array('model'=>$model));
	}
	
	public function createFolder($path)
	{
		if (!file_exists(dirname($path)))
		{ 
			mkdir(dirname($path), 0777, true);
		} 
	}
	
	public function actionUploadFile()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			header("Cache-Control: no-cache, must-revalidate");
			header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
			
			if(isset($_GET['uid'])){
		   		$status = apc_fetch('upload_' . $_GET['uid']);
		   		echo CJSON::encode($status);
		   	}
		}
		
	}
}

?>